// 请求地址
const baseUrl = '';

// 请求头
const header = {
    'X-Requested-With': 'XMLHttpRequest',
};

const getErrorMsg = (code) => {
	let errorMsg = '';
	
	switch(code)
	{
	    case 400:
	        errorMsg = '错误请求';
	        break;
	    case 401:
	        errorMsg = '未授权，请重新登录';
	        break;
	    case 403:
	        errorMsg = '拒绝访问';
	        break;
	    case 404:
	        errorMsg = '请求错误,未找到该资源';
	        break;
	    case 405:
	        errorMsg = '请求方法未允许';
	        break;
	    case 408:
	        errorMsg = '请求超时';
	        break;
	    case 500:
	        errorMsg = '服务器端出错';
	        break;
	    case 501:
	        errorMsg = '网络未实现';
	        break;
	    case 502:
	        errorMsg = '网络错误';
	        break;
	    case 503:
	        errorMsg = '服务不可用';
	        break;
	    case 504:
	        errorMsg = '网络超时';
	        break;
	    case 505:
	        errorMsg = 'http版本不支持该请求';
	        break;
	
	    default:
	        errorMsg = `连接错误${code}`;
	}
	
	return errorMsg;
}

const post = (data = {}) => {
    return new Promise((resolve, reject) => {
        uni.request({
            url: baseUrl ? baseUrl + data.url : data.url,
            data: data.params,
            header: header,
            method: 'POST',
            success: (res) => {
                if(res.statusCode === 200)
                {
                    resolve(res.data);
                }else{
                    let errorMsg = getErrorMsg(res.statusCode);

                    reject(errorMsg);
                }
            },
            fail: (err) => {
                reject(err);
            },
        });
    });
};

const install = (Vue, vm) => {
    Vue.prototype.$Http = {
        post
    };
};

export default {
    post,
    install
};
